package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/utils/captcha"
	"html/template"
	"src/gitee.com/wx_e6924dbcd0/notebook/models"
	"strconv"
)

type LoginMainController struct {
	beego.Controller
}

//定义一个结构体
type User struct {
	U_id      int64  `form:"id" json:"id"`
	Username  string `form:"username" json:"username"`
	Passwd    string `form:"passwd" json:"passwd"`
	Sex       string `form:"sex" json:"sex"`
	Logindate string `form:"logindate" json:"logindate"`
	Regtime   string `form:"regtime" json:"regtime"` // LoginTime=> login_time
	Status    int64  `form:"status" json:"status"`
	Headpic   string `form:"headpic" json:"headpic"`
	//Hobby  []string  `form:"hobby" json:"hobby"`
}

func (c *LoginMainController) Get() {
	//先去查询memcache
	// 判断cookies, 来确定是否打开
	// 1、 或取 cookies, 2 Y , 跳到index,
	//usname,_ :=  c.GetSecureCookie("111","username")
	//passwd,_ :=  c.GetSecureCookie("111","passwd")
	id := c.Ctx.GetCookie("userId")
	if id != "" && id != "null" {
		userId, erru := strconv.Atoi(id)
		if erru != nil {
			log := models.UitlLog()
			log.Error("数据转换 failed", erru.Error())
			return
		}
		cached := true
		userInfo := models.GetUserInfo(int64(userId), cached)
		if userInfo != nil {
			c.TplName = "base_login.html"
			return
		}
	}

	//获取Session
	//usname := c.GetSession("username")
	//passwd := c.GetSession("passwd")
	//fmt.Print(usname)
	//if userid != "" {
	//	//c.Ctx.Redirect(302, "/main/get")
	//	//c.Redirect("base_login.html",302)
	//	c.TplName = "base_login.html"
	//	return
	//}

	c.TplName = "login.html"

}

var cpt *captcha.Captcha

func init() {
	// use beego cache system store the captcha data
	store := cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/captcha/", store)
}

func (c *LoginMainController) DoLogin() {
	//验证码验证
	if c.Ctx.Input.Method() == "POST" {
		//// 验证输入
		yorn := cpt.VerifyReq(c.Ctx.Request)
		c.Data["Success"] = yorn
		fmt.Printf("%T,%v", yorn, yorn)
		//var x string= "0"
		if yorn == false {
			c.Ctx.SetCookie("fail", "1", 1)
			c.Redirect("login.html", 302)
			return
		}
	}
	user := User{} //实例化结构体
	if err := c.ParseForm(&user); err != nil {
		//c.Ctx.WriteString("post提交失败")
		log := models.UitlLog()
		log.Error("数据获取错误 err" + err.Error())
		return
	}
	fmt.Printf("%v", user)
	//c.Ctx.WriteString("解析post提交成功")
	//防xss漏洞
	usname := template.HTMLEscapeString(user.Username)
	passwd := template.HTMLEscapeString(user.Passwd)
	if usname == "admin" {
		err1 := models.InSu(usname, passwd)
		if err1 != nil {
			log := models.UitlLog()
			log.Error("InSu err" + err1.Error())
			c.Ctx.SetCookie("Login_sta", "0", 2)
			c.Ctx.Redirect(302, "/login")
			return
		}
		//设置中文Cookie，并且加密，第一个参数表示加密密钥“ aaa ”
		//c.Ctx.SetSecureCookie("111","username",usname,10)
		//c.Ctx.SetSecureCookie("111","passwd",passwd,10)
		c.Ctx.SetCookie("userId", "666")
		c.Ctx.SetCookie("headpic", "user.PNG")
		//c.SetSession("username",usname)
		//c.SetSession("passwd",passwd)
		//封装成json数据
		c.Ctx.SetCookie("Status", "0", 2)
		c.Data["json"] = user
		//c.ServeJSON()
		c.Redirect("/login", 302)
		return
	}
	users, err2 := models.InUser(usname, passwd)
	if err2 != nil {
		log := models.UitlLog()
		log.Error("InUser err" + err2.Error())
		c.Ctx.SetCookie("Login_sta", "0", 2)
		c.Ctx.Redirect(302, "/login")
		//fmt.Println("找不到主键")
		return
	}
	////设置中文Cookie，并且加密，第一个参数表示加密密钥“ aaa ”
	//c.Ctx.SetSecureCookie("111","username",usname,10)
	//c.Ctx.SetSecureCookie("111","passwd",passwd,10)
	userId := strconv.FormatInt(users.Userid, 10)
	c.Ctx.SetCookie("userId", userId)
	c.Ctx.SetCookie("headpic", users.Headpic)
	if users.Status > 0 {
		c.Ctx.SetCookie("Status", "1")
	}
	//获取Session
	//c.SetSession("user",users)
	//c.SetSession("username",usname)
	//c.SetSession("passwd",passwd)
	//c.SetSession("u_id",users.Userid)
	//封装成json数据
	user.U_id = users.Userid
	user.Sex = users.Sex
	user.Logindate = users.Logindate
	user.Regtime = users.Regtime
	user.Headpic = users.Headpic
	//存入memache
	cached := false
	userInfo := models.GetUserInfo(users.Userid, cached)
	if userInfo != nil {
		c.TplName = "base_login.html"
	}
	c.Data["json"] = user
	//c.ServeJSON()
	//c.Redirect("base_login.html",302)
	c.Ctx.Redirect(302, "/login")
}
